package com.studay;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class LubanBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")) {
            System.out.println("初始化后");

            Object o = Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),

                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws
                                Throwable {

                            System.out.println("代理逻辑1");

                            method.invoke(bean, args);
                            System.out.println("代理逻辑2");
                            return null;
                        }
                    }
            );
            return o;
        }
        return null;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")) {
            System.out.println("初始化前");
        }
        return bean;// null postconstruct 初始化前  一个一个的执行 如果返回 null 后面的 就执行不了了。很多的beanpostprocessor
    }

//    @Override
//    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
//        if (beanName.equals("userService")) {
//            System.out.println("实例化后");
//        }
//
//        return true;
//    }
//
//
//    @Override
//    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
//        if (beanName.equals("userService")) {
//            System.out.println("实例化前");
//        }
//        return null;
//    }

}
